package com.tang.module.useapi.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.common.constant.DictConstant;
import com.tang.common.exception.GlobalException;
import com.tang.common.utils.cache.DictCache;
import com.tang.module.useapi.mapper.UseApiMapper;
import com.tang.module.useapi.entity.UseApi;
import com.tang.module.useapi.search.UseApiSearch;
import com.tang.module.useapi.service.UseApiService;
import com.tang.module.useapi.vo.UseApiVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统使用的外部接口(UseApi)表服务实现类
 *
 * @author tang
 * @since 2022-04-02 16:49:13
 */
@Service("useApiService")
public class UseApiServiceImpl extends ServiceImpl<UseApiMapper, UseApi> implements UseApiService {

    @Resource
    private UseApiMapper useApiMapper;

    @Override
    public IPage<UseApiVo> list(IPage<UseApiVo> page, UseApiSearch useApiSearch) {
        return useApiMapper.list(page, useApiSearch);
    }

    @Override
    public List<UseApiVo> tree(UseApiSearch useApiSearch) {
        IPage<UseApiVo> list = useApiMapper.list(new Page<>(1, 100000), useApiSearch);
        //填充数据字典
        list.getRecords().forEach(useApiVo ->
                useApiVo.setMethodTypeName(
                        useApiVo.getMethodType() == null ? null :
                        DictCache.getValue(DictConstant.HTTP_TYPE, Math.toIntExact(useApiVo.getMethodType()))));
        return this.createTree(0L,list.getRecords());
    }

    @Override
    public List<UseApiVo> createTree(Long pid, List<UseApiVo> list) {
        List<UseApiVo> voList = new ArrayList<>();
        for (UseApiVo useApiVo : list) {
            if (useApiVo.getParentId().equals(pid)){
                voList.add(useApiVo);
                useApiVo.setChildren(createTree(useApiVo.getId(),list));
            }
        }
        return voList;
    }

    @Override
    public boolean status(UseApi useApi) {
        //变更为开启
        if (useApi.getEnable() == 1){
            //查询该类接口是否已经有开启的接口，如果有，则不能再次启用新接口
            Integer integer = useApiMapper.selectCount(Wrappers.<UseApi>lambdaQuery().
                    eq(UseApi::getParentId, useApi.getParentId()).
                    eq(UseApi::getEnable, 1).ne(UseApi::getId, useApi.getId())
            );
            if (integer != 0){
                throw new GlobalException("该类接口已经有启用的接口，无法再次启用新接口");
            }
        }
        //变更为关闭，或者变更为开启，但是原接口类型没有开启的接口时直接更新即可
        return useApiMapper.updateById(useApi) == 1;
    }
}
